'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
    //注册
    async registry() {
        //1.接收前端传递的参数
        //2.容错处理  
        //3.排重  从userlist表去查是否该用户名已经存在，如果不存在，就注册，否则存在，不注册
        //4.注册  try ... catch
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && /\d{6,8}/.test(password)){
            //排重
            let target = await service.user.selectUser(username);
            console.log(target);
            if(target.length){
                //存在
                ctx.body = {
                    code:4,
                    msg:'该用户已存在'
                }
            }else{
                //不存在
                try{
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }

        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        //1.接收传递的参数
        //2.容错
        //3.登录
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && /\d{6,8}/.test(password)){
            let hmcPwd = ctx.helper.hmc(password);
            let list = await service.user.login(username,hmcPwd);
            if(list.length){
                ctx.body = {
                    code:1,
                    msg:'登录成功'
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
